package cn.com.wxd.service.dispatch.engine;

import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.service.dispatch.logger.CustomTaskLogger;
import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.JsonUtil;
import cn.com.wxd.common.file.ReadConfigFile;
import cn.com.wxd.common.XmlUtil;
import cn.com.wxd.common.file.MyFileUtil;
import cn.com.wxd.common.net.HttpClientUtil;

/**
 * Created by ComXu on 2017/5/17.
 */
public class TaskRun {

    private static final Logger log = LoggerFactory.getLogger(TaskRun.class);

    public void run(String taskId, String taskName, String script) {
        BSFManager manage = new BSFManager();
        try {
            //注册一些内置对象在script中方便使用
            manage.declareBean("out", System.out, System.out.getClass());
            manage.declareBean("log", new CustomTaskLogger(taskId, taskName), CustomTaskLogger.class);
            manage.declareBean("charUtil", new CharUtil(), CharUtil.class);
            manage.declareBean("dateUtil", new DateUtil(), DateUtil.class);
            manage.declareBean("jsonUtil", new JsonUtil(), JsonUtil.class);
            manage.declareBean("xmlUtil", new XmlUtil(), XmlUtil.class);
            manage.declareBean("globalConfig", new ReadConfigFile(), ReadConfigFile.class);
            manage.declareBean("httpClient", new HttpClientUtil(), HttpClientUtil.class);
            manage.declareBean("fileUtil", new MyFileUtil(), MyFileUtil.class);
        } catch (BSFException e) {
            log.error("脚本注册内置对象出现异常", e);
        }
        //  先引入js.jar
        // : 返回script的值,以object的形式.
        //		manage.exec( “javascript”, XX, YY, ZZ, script):　执行这script.返回空!
        //		第一个参数javascript可以换成其它如perl, python, tcl……
        //		XX: 没作用，任何string都行.
        //		YY: The line number, 通常为0,
        //		ZZ: The character position of the given script in the input source
        //			(these arguments are for error reporting), 通常为0最后一个参数是要执行的script语句, 是String就行了.
        //
        try {
            Object obj = manage.eval("javascript", "", 0, 0
                    , script);
                log.debug("任务号：" + taskId + "，任务名称：" + taskName + ",脚本运行完毕!返回：" + obj.toString());
        } catch (BSFException e) {
            log.error("任务号：" + taskId + "，任务名称：" + taskName + ",脚本运行错误:" + script, e);
        }
    }
}
